$(document).ready(function() {

});


/** 清空提示*/
$('.wrapper').on("click","#emptyTips",function () {
    console.log("点击清空")
    var searchIP= $("[name='searchIP']");
    if (searchIP.length < 1){
        return;
    }
    showModal("#searchEmpty");
})

/* 清空 */
// $('#empty').click(function () {
$('.wrapper').on("click","#empty",function () {
    $('input[name="searchIP"]').parent().parent().remove();
    searchAll();
    hideModal("#searchEmpty");
})

/* 切换标签 */
function navigation(states) {

    var searchIP= $("[name='searchIP']");
    var searchType = $("#searchType").val();   // 搜索类型
    var topCondition = $("#topCondition").val();   // 搜索条件
    // if (searchIP.length < 1){
    //     errMsg("请添加搜索内容")
    //     return;
    // }

    var snIpAddre = "";
    for(var x=0;x<searchIP.length;x++){
        if(searchIP[x].checked) {
            snIpAddre = snIpAddre + $(searchIP[x]).attr("search_sn_ip") + ",";
        }
    }

    $("#all").prop("checked",false)
    var node1=document.getElementsByName("all");
    allCheck(node1);

    $.ajax({
        type : "post",
        url : basePath + "/worker/ajaxSearchWorkerList",
        data : { "snIpAddre":snIpAddre,"states":states,"searchType":searchType,"topCondition":topCondition},
        dataType: "html",
        success: function (txt) {
            if(txt == "error"){
                // $("#bidForm").submit();   active show
            }else{
                // $("#show1").html(txt);
                $("#workerListTwo").html(txt);
                if (states == '全部'){

                    $("#whole").removeClass("active show");
                    $("#normal").removeClass("active show");
                    $("#insufficientCalculation").removeClass("active show");
                    $("#dropLine").removeClass("active show");
                    $("#fail").removeClass("active show");

                    $("#whole").addClass("active");
                    $("#whole").addClass("show");
                }else  if (states == '正常'){
                    $("#whole").removeClass("active show");
                    $("#normal").removeClass("active show");
                    $("#insufficientCalculation").removeClass("active show");
                    $("#dropLine").removeClass("active show");
                    $("#fail").removeClass("active show");

                    $("#normal").addClass("active");
                    $("#normal").addClass("show");
                }else  if (states == '算力不足'){
                    $("#whole").removeClass("active show");
                    $("#normal").removeClass("active show");
                    $("#insufficientCalculation").removeClass("active show");
                    $("#dropLine").removeClass("active show");
                    $("#fail").removeClass("active show");

                    $("#insufficientCalculation").addClass("active");
                    $("#insufficientCalculation").addClass("show");
                }else  if (states == '掉线'){
                    $("#whole").removeClass("active show");
                    $("#normal").removeClass("active show");
                    $("#insufficientCalculation").removeClass("active show");
                    $("#dropLine").removeClass("active show");
                    $("#fail").removeClass("active show");

                    $("#dropLine").addClass("active");
                    $("#dropLine").addClass("show");
                }else  if (states == '失败'){
                    $("#whole").removeClass("active show");
                    $("#normal").removeClass("active show");
                    $("#insufficientCalculation").removeClass("active show");
                    $("#dropLine").removeClass("active show");
                    $("#fail").removeClass("active show");

                    $("#fail").addClass("active");
                    $("#fail").addClass("show");
                }

            }
        }
    });

}

/* 刷新 （获取最新的数据） 监听*/
// $('#refresh').click(function () {
$('.wrapper').on("click","#refresh",function () {
    console.log("刷新矿机，，，监听");
    var customerID = $("#customerID").val();   /*客户号*/
    var workerName = $("#workerName").val();    /*子账号*/
    var workerIPStart = $("#workerIPStart").val();      /*IP开始*/
    var workerIPEnd = $("#workerIPEnd").val();      /*IP结束*/
/**      1111111        */
    var searchIP= $("[name='searchIP']");
    if (searchIP.length < 1){
        return;
    }

    //获取是否选中
    var isChecked = $("input[name='searchIP']").is(':checked')
    if(!isChecked){
        return;
    }

    var snIpAddre = "";
    for(var x=0;x<searchIP.length;x++){
        if(searchIP[x].checked) {
            snIpAddre = snIpAddre + $(searchIP[x]).attr("search_sn_ip") + ",";
        }
    }
    console.log(snIpAddre)
    /**      22222222        */
    $.ajax({
        type : "post",
        url : basePath + "/worker/ajaxWorkerList",
        data : { "snIpAddre":snIpAddre},
        dataType: "json",
        success: function (data) {
            sucMsg('刷新成功');
            navigation("全部");
            // $("#query").click();
        }
    });
});

/** 全选 */
function allCheck(node1){
    var node=document.getElementsByName("mm");
    var restart = false;//用于遍历是否是全部变量设置
    for (var x = 0; x < node.length; x++) {
        node[x].checked=node1.checked;
    }
}

/** 单个选择 */
function chose(node){
    var flag=true;//用于遍历是否是全部变量设置

    var allM=document.getElementsByName("all")[0];
    var node=document.getElementsByName("mm");

    for (var x = 0; x < node.length; x++) {
        if(node[x].checked==false){//只要有一个没选中，就退出遍历，标记设置为false
            flag=false;
            break;
        }
    }

    if(flag){
        allM.checked=true;
    }else{
        allM.checked=false;
    }

}

/** 重启矿机提示信息 */
$('.wrapper').on("click","#restartTips",function () {
    console.log("点击重启1")
    var names = $("[name='mm']")
    if (names.length == 0 || $('input[name="mm"]:checked').length == 0) {
        errMsg("没有需要重启的矿机")
        return;
    }
    for (var x = 0; x < names.length; x++) {
        if (names[x].checked) {//选中的全部加起来
            if ($(names[x]).attr("sn_ip").length < 20) {
                errMsg("失败矿机不能操作")
                return;
            }
        }
    }
    showModal("#searchDelete2");
});

/** 重启 获取所有选中项 */
// $('#restart').click(function () {
$('.wrapper').on("click","#restart",function () {
    console.log("点击重启1")
    var names= $("[name='mm']")
    if (names.length == 0 || $('input[name="mm"]:checked').length == 0){
        errMsg("没有需要重启的矿机")
        return;
    }
    var ipAddre = "";
    console.log(names)
    for(var x=0;x<names.length;x++){
        if(names[x].checked){//选中的全部加起来
            if ($(names[x]).attr("sn_ip").length < 20){
                errMsg("失败矿机不能操作")
                return;
            }
            ipAddre = ipAddre + $(names[x]).attr("sn_ip") + ",";
        }
    }
    ipAddre = ipAddre.substring(0,ipAddre.length - 1);

    console.log("开始发送请求")
    $.ajax({
        type : "post",
        url : basePath + "/worker/ajaxWorkerRestart",
        data : {"snip":ipAddre},
        dataType: "json",
        success : function(res){
            if(res.bizSuccess){
                $("#searchDelete2").click();
                sucMsg("重启矿机成功，请稍后查看")
            } else{
                $("#searchDelete2").click();
                errMsg(res.errorMsg);
            }

        }
    });
});

/** 配置矿池*/
// $('#minePoolModify').click(function () {
$('.wrapper').on("click","#minePoolModify",function () {
    console.log("点击配置矿池")
    var names= $("[name='mm']");        // 多个IP
    var ipAddre = "";
    console.log(names)
    for(var x=0;x<names.length;x++){
        if(names[x].checked){//选中的全部加起来
            ipAddre = ipAddre + $(names[x]).attr("sn_ip") + ",";
        }
    }
    ipAddre = ipAddre.substring(0,ipAddre.length - 1);

    // var ipAddre = $("#snIP").val();   // 多个IP
    var minePool1= $("#minePool1").val();           // 矿池1
    var account1= $("#account1").val();             // 账号1
    var password1= $("#password1").val();           // 密码1

    var minePool2= $("#minePool2").val();           // 矿池2
    var account2= $("#account2").val();             // 账号2
    var password2= $("#password2").val();           // 密码2

    var minePool3= $("#minePool3").val();           // 矿池3
    var account3= $("#account3").val();             // 账号3
    var password3= $("#password3").val();           // 密码3

    if(((minePool1 == "" || minePool1 == 0) && (account1 == "" || account1 == 0) && (password1 == "" || password1 == 0)) || (minePool2 == "" || minePool2 == 0) && (account2 == "" || account2 == 0) && (password2 == "" || password2 == 0) || ((minePool3 == "" || minePool3 == 0) && (account3 == "" || account3 == 0) && (password3 == "" || password3 == 0))){
        errMsg("至少配置一个矿池信息")
        return;
    }

    $.ajax({
        type : "post",
        url : basePath + "/worker/ajaxWorkerMinePoolModify",
        data : {"snip": ipAddre,"minePool1":minePool1,"account1":account1,"password1":password1,"minePool2":minePool2,"account2":account2,"password2":password2,"minePool3":minePool3,"account3":account3,"password3":password3},
        dataType: "json",
        success : function(txt){
            $("#signup-change").click();
            sucMsg("配置矿池成功");
        }
    });
});


/** 新增 IP段 保存 */
$('#addIPAddress').click(function () {
    console.log("新增 IP段 保存")
    $("#iPAddressMessage").empty();
    var idSn = $("#snList").val()
    var customerID = $("#example-customerList").val()

    if(idSn==null || idSn == undefined || idSn==""){
        $("#iPAddressMessage").html("请选择矿场SN码");
        return;
    }

    if(customerID==null || customerID == undefined || customerID==""){
        $("#iPAddressMessage").html("请选择客户");
        return;
    }

    var ipStart= $("[name='ipStart']");        // 多个IP
    var ipEnd= $("[name='ipEnd']");             // 多个IP
    var ipAddre = "";
    for(var x=0;x<ipStart.length;x++){
        // if (!checkIsIP(ipStart[x].value) || !checkIsIP(ipEnd[x].value)){
        //     $.NotificationApp.send("错误","IP格式错误，请检查重试","top-center","rgba(0,0,0,0.2)","error");
        //     return
        // }
        ipAddre = ipAddre + ipStart[x].value+"-"+ ipEnd[x].value  + ",";
        console.log(ipStart[x].value);
    }


    ipAddre = ipAddre.substring(0,ipAddre.length - 1);

    $.ajax({
        type : "post",
        url : basePath + "/worker/ajaxAddIPRegion",
        data : {"idSn": idSn,"customerID":customerID,"ipAddre":ipAddre},
        dataType: "json",
        success : function(txt){
            console.log("跳转页面")
            $("#signup-addIPAddress").click();
        }
    });

    $("#signup-addIP").click();
});


/** 添加或者删除页面上的IP段 */
function addAndAelete(e) {
    var ff = $(e).parents(".align-items-center");
    var f = $(e).parent();
    $(e).remove();
    f.append("<button type=\"button\" style=\"background-color:#d65849\" class=\"btn btn-primary mb-1\" onclick=\"kill(this)\" >&times;</button>");
    ff.after("<div class=\"align-items-center\"><input type=\"text\" class=\"form-control mb-2\" name=\"ipStart\" style=\"width:40%;padding:0.2rem 0.7rem;display:inline-block;text-align:center;font-size:1.2rem;color:#212121;font-weight:400;\" placeholder=\"192.168.0.1\"><span style=\"width:2%;padding:0.1rem 0.1rem;text-align:center;\"> 至</span><input type=\"text\" class=\"form-control\" name=\"ipEnd\" placeholder=\"192.168.0.90\" style=\"width:40%;padding:0.2rem 0.7rem;display:inline-block;text-align:center;font-size:1.2rem;color:#212121;font-weight:400;\"> <button type=\"button\" class=\"btn btn-primary mb-1\" onclick=\"addAndAelete(this)\" ><i class=\"mdi mdi-plus\"></i></button></div>");
}

function kill(e) {
    var f = $(e).parents(".align-items-center");
    f.remove();
}

//校验是否IP地址
function checkIsIP(s) {
    // var patrn = /^[0-9.]{1,20}$/;
    var patrn = /(?=(\b|\D))(((\d{1,2})|(1\d{1,2})|(2[0-4]\d)|(25[0-5]))\.){3}((\d{1,2})|(1\d{1,2})|(2[0-4]\d)|(25[0-5]))(?=(\b|\D))/;
    if (!patrn.exec(s)) return false
    return true
}

// 查询删除某一个节点
// $('#searchDelete').click(function () {
$('.wrapper').on("click","#searchDelete",function () {

    var searchIP= $("[name='searchIP']");        // 多个IP
    //获取是否选中
    var isChecked = $("input[name='searchIP']").is(':checked')
    if(isChecked){//选中的全部加起来
        for(var x=0;x<searchIP.length;x++){
            if(searchIP[x].checked){//选中的全部加起来
                console.log($(searchIP[x]).attr("value"))
                var queryIDs = $(searchIP[x]).attr("value");
                $.ajax({
                    type : "post",
                    url : basePath + "/worker/ajaxRemove",
                    data : { "queryIDs":queryIDs},
                    dataType: "json",
                    success: function (res) {
                        // if(res.bizSuccess){
                        //     sucMsg("移除成功")
                        // }else {
                        //     errMsg("移除失败，请重试")
                        //     return;
                        // }
                    }
                });
                /* 删除节点 */
                $(searchIP[x]).parent().parent().remove();
            }
        }
        $('#searchDelete1').click();
        sucMsg("移除成功")
        searchAll();
    }else {
        errMsg("请选择需要删除的IP段");
    }
})

/** 移除搜索条件*/
$('.wrapper').on("click","#searchDeleteTips",function () {
    var searchIP= $("[name='searchIP']");        // 多个IP
    //获取是否选中
    var isChecked = $("input[name='searchIP']").is(':checked')
    if(isChecked){//选中的全部加起来
        showModal("#searchDelete1");
    }else {
        errMsg("请选择需要删除的IP段");
    }
})


// 查询添加客户IP
$('#workerListSearchAddCustomerSub').click(function () {
    /* 多个用户的ID */
    var customers = $("#search-customers").val();   // 数组
    var count = $("input[name='searchIP']").length;
    ++count;
    if (customers.length < 1){
        errMsg("请选择客户")
    }
    $.ajax({
        type : "post",
        url : basePath + "/worker/ajaxWorkerAddCustomerIP",
        data : {"customers":customers},
        dataType: "json",
        traditional: true,
        success : function(res){
            console.log(res)
            if(res.bizSuccess){
                var condition = res.dateList;
                // console.log(condition.length)
                if (condition.length < 1){
                    $("#workerListSearchAddCustomer").click();
                    errMsg("该用户没有添加IP,请在设置添加");
                    return;
                }
                $.each(res.dateList, function(index, item){
                    ++count;
                    var con = "";
                    con += "<tr style=\"height: 1rem;\" ><td><input onclick=\"searchAll()\" type=\"checkbox\" value=\""+item.queryID+"\" search_sn_ip=\""+item.snIP+"\" name=\"searchIP\" id=\""+count+"\"><td>"+item.ipPart+"</td><td>"+item.realName+"</td><td>"+item.snNameSn+"</td></tr>"
                        // con += "<tr style=\"height: 1rem;\" ><td><input onclick=\"searchAll()\" type=\"checkbox\" search_sn_ip=\""+item.sn+"_"+item.region+"\" name=\"searchIP\" id=\"search"+count+"\"><td>"+item.region+"</td><td>"+item.realName+"</td><td>"+item.snName+"("+item.sn+")</td></tr>";
                    $('#search-tabody').append(con);
                    $("#workerListSearchAddCustomer").click();
                });
            }
            else{
                errMsg(res.errorMsg);
            }
        }
    });
})


// 查询添加IP
$('#workerListSearchAddIPSub').click(function () {
    /* 多个用户的ID */
    var searchAddSn = $("#searchAddSn  option:selected").text();
    var equipmentID = $("#searchAddSn  option:selected").val();
    var searchIPStart = $("#searchIPStart").val();   // IP开始
    var searchIPEnd = $("#searchIPEnd").val();   // IP结束
    var count = $("input[name='searchIP']").length;
    ++count;
    console.log(searchAddSn)
    console.log(searchIPStart)
    console.log(searchIPEnd)
    if(searchAddSn==null || searchAddSn==undefined || searchAddSn==""){
        errMsg("请选择SN码")
        return;
    }
    if(searchIPStart==null || searchIPStart==undefined || searchIPStart==""){
        errMsg("IP1不能为空")
        return;
    }
    if(searchIPEnd==null || searchIPEnd==undefined || searchIPEnd==""){
        errMsg("IP2不能为空")
        return;
    }
    if (!checkIsIP(searchIPStart)){
        errMsg("IP1格式有误，请重新添加")
        return;
    }
    if (!checkIsIP(searchIPEnd)){
        errMsg("IP2格式有误，请重新添加")
        return;
    }

    $.ajax({
        type : "post",
        url : basePath + "/worker/ajaxQueryAddIP",
        data : {"equipmentID":equipmentID,"searchIPStart":searchIPStart,"searchIPEnd":searchIPEnd},
        dataType: "json",
        traditional: true,
        success : function(res){
            if(res.bizSuccess){
                var con = "<tr style=\"height: 1rem;\" ><td><input onclick=\"searchAll()\" value=\""+res.successMsg+"\" type=\"checkbox\" search_sn_ip=\""+searchAddSn+"_"+searchIPStart+"-"+searchIPEnd+"\" name=\"searchIP\" id=\""+count+"\"><td>"+searchIPStart+"-"+searchIPEnd+"</td><td>"+""+"</td><td>"+searchAddSn+"</td></tr>";
                $('#search-tabody').append(con);
                $("#workerListSearchAddIP").click();
            }
            else{
                $("#workerListSearchAddIP").click();
                errMsg("添加失败，请重新添加");
            }
        }
    });
})

/* 搜索 */
// $('#query').click(function () {
$('.wrapper').on("click","#query",function () {
        console.log("搜索")
        var searchIP= $("[name='searchIP']");
        if (searchIP.length < 1){
            errMsg("请添加搜索内容")
            return;
        }

        //获取是否选中
        var isChecked = $("input[name='searchIP']").is(':checked')
        if(!isChecked){
            errMsg("请选择需要查询的IP段");
            return;
        }

        var snIpAddre = "";
        for(var x=0;x<searchIP.length;x++){
            if(searchIP[x].checked) {
                snIpAddre = snIpAddre + $(searchIP[x]).attr("search_sn_ip") + ",";
            }
        }

        $.ajax({
            type : "post",
            url : basePath + "/worker/ajaxSearchWorkerList",
            data : { "snIpAddre":snIpAddre,"searchType":"other"},
            dataType: "html",
            success: function (txt) {
                if(txt == "error"){
                    // $("#bidForm").submit();
                }else{
                    $("#workerListTwo").html(txt);
                }
            }
        });

})



/** 查询条件 全选 */
// $('#customCheck1').click(function () {
$('.wrapper').on('click','#customCheck1',function () {
    console.log("点击全选查询")
    if(this.checked) {
        console.log("点击全选查询111")
        $("input[name='searchIP']").prop('checked',true);
    }else {
        console.log("点击全选查询222")
        $("input[name='searchIP']").prop('checked',false);
    }
})

/*是否选中全选*/
function searchAll() {
    if (($('input[name="searchIP"]:checked').length < $('input[name="searchIP"]').length) || ($('input[name="searchIP"]:checked').length == 0)){
        $('input[name="customCheck1"]').prop("checked", false)
     }
    if ($('input[name="searchIP"]:checked').length == $('input[name="searchIP"]').length && ($('input[name="searchIP"]:checked').length > 0)){
        $('input[name="customCheck1"]').prop("checked", true)
    }
}

/**  配置矿池验证 */
$('.wrapper').on("click","#workerConfigure",function () {
// $('#workerConfigure').click(function () {
    console.log("配置矿池验证")
    var names= $("[name='mm']")
    if (names.length == 0  || $('input[name="mm"]:checked').length == 0){
        errMsg("请选择矿机")
        return;
    }
    var ipAddre = "";
    console.log(names)
    for(var x=0;x<names.length;x++){
        if(names[x].checked){//选中的全部加起来
            if ($(names[x]).attr("sn_ip").length < 20){
                errMsg("失败矿机不能操作")
                return;
            }
        }
    }
    console.log("弹框")
    showModal("#signup-change");

})

function signupAddIPAddress(selectorID) {
	// 校验是否绑定sn
	$.ajax({
		type:"GET",
		url:basePath + "/equipment/ajaxCheckBindEquipment",
		dataType:"json",
		success: function(data) {
			if(data.bizSuccess) {
				showModal(selectorID);
			} else {
				showModal("#toBindSn");
			}
		}
	})
}












